__version__ = "$Revision: 120 $"
__date__ = "$Date: 2011-07-31 16:47:57 +0200 (So, 31 Jul 2011) $"
__lastChangedBy__ = "$Author: wolters@3sconsult.de $"
__repository__ = "$HeadURL: https://sir3spy.googlecode.com/svn/Sir3sPy/Utils/trunk/Db.py $"

"""Module Md.

Description
-----------
    - Class(es): 
        -- Md.
    - Infile (demonstration of the) modules usage.
"""

import os
import sys
import logging

import networkx as nx
import collections

from Sir3sPy.Utils.Db import DbOra

class Md:
    """Graph oriented model class. 
    """    
              
    def __init__(self,connectionString='myDb/myPw@xe',fileWithSelectAllEdgesCmd='C:/Python31/Lib/site-packages/Sir3sPy/Data/Sir3sDbSelectOneModelAllEdges.sql',**sqlSelectParams):
        """        
        Parameter
        ---------
            <connectionString>    
                - Oracle connectionString to an Oracle database containing one ore more models
                    - examples:
                         - user/password@server
                         - myDb/myPw@xe     
            <fileWithSelectAllEdgesCmd>    
                - Sir3sDbSelectOneModelAllEdges.sql compliant file with on select command delivering all data for all edges of one model
            <sqlSelectParams>    
                - Parameter (key=value) required in fileWithSelectAllEdgesCmd                                         
        """           

        fileName =__file__                
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'.__init__'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)              
        
        try:                                   
            logger.debug('Start:') 
            
            self.G=None
            db=DbOra(connectionString)
            if sqlSelectParams=={}:
                p=eval("{'MId':'M-1-0-1'}")                
            else:
                p=sqlSelectParams
            attrNames,edgeData=db.executeSelectScript(fileWithSelectAllEdgesCmd,**p)
            Edge = collections.namedtuple('Edge', attrNames)
            self.G = nx.MultiDiGraph()
            self.G.add_edges_from([(edge[attrNames.index('NIDSRC')],edge[attrNames.index('NIDSNK')],{'Edge':Edge._make(edge)}) for edge in edgeData])
            
            self.GNet=nx.MultiDiGraph(self.G)
            
            contEdges=[]
            for e in self._iterContEdges():
                contEdges.append(e)
                
            self.GNet.remove_edges_from(contEdges)     
    
        except:
            logger.error('Exception.')                 
            raise
        finally:
            logger.debug('_Done:')                                       

    def _allEdges(self):
        """        
                                     
        """           

        fileName =__file__                
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'._allEdges'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)              
        
        try:                                   
            logger.debug('Start:') 

            for n,nbrs in self.G.adjacency_iter():
                for nbr,eattr in nbrs.items():
                    e=eattr[0]
                    e2=e['Edge']
                    logger.debug('{:12s} {:12s} {:4s}'.format(n,nbr,e2.OTYP))
                    
        except:
            logger.error('Exception.')                 
            raise
        finally:
            logger.debug('_Done:')      

    def _iterContEdges(self):
        """        
                                     
        """           

        fileName =__file__                
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'._iterContEdges'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)              
        
        try:                                   
            logger.debug('Start:') 

            for n,nbrs in self.G.adjacency_iter():
                for nbr,eattr in nbrs.items():
                    e=eattr[0]
                    e2=e['Edge']
                    if e2.OCOIND==1:
                        #yield self.G[n][nbr]
                        yield (n,nbr) 
                        #logger.debug('{:12s} {:12s} {:4s} {:s}'.format(n,nbr,e2.OTYP,e2.OCONAM))
                    
        except:
            logger.error('Exception.')                 
            raise
        finally:
            logger.debug('_Done:')                   

    def _allSources(self):
        """        
                                     
        """           

        fileName =__file__                
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'._allSources'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)              
        
        try:                                   
            logger.debug('Start:') 

            for n,nbrs in self.G.adjacency_iter():
                pre=self.G.predecessors(n)                
                if len(pre)==0:
                    logger.debug('{:12s} Source'.format(n))
                    
        except:
            logger.error('Exception.')                 
            raise
        finally:
            logger.debug('_Done:')        


                                                   
if __name__ == "__main__":

    # logging configuration
    filename=__file__
    loggerName=filename[__file__.find('Sir3sPy'):].replace('.py','').replace('\\','.').replace('/','.')
    logging.getLogger(loggerName).addHandler(logging.NullHandler())
    # configure logfile
    moduleName,ext=os.path.splitext(os.path.basename(__file__))     
    logFileName = os.path.join(os.getcwd(),moduleName+'.log') 
    # configure logging       
    logging.basicConfig(filename=logFileName,filemode='w',level=logging.DEBUG,format="%(asctime)s ; %(name)-60s ; %(levelname)-7s ; %(message)s")    
        
    try:
        logger = logging.getLogger(loggerName)
        returnValue=None          
        md = Md() 
        md._allSources()
        #for e in md._iterContEdges():
        #    pass
        returnValue=1  
        sys.exit(returnValue)            
    except SystemExit:        
        pass    
    except:
        returnValue=-1 
        logger.error('Exception.') 
    finally:                                         
        sys.exit(returnValue)                